# -*- coding: utf-8 -*-
"""
SmarTest 全局配置文件
"""

import os
from pathlib import Path

# 项目根目录
WORK_PATH = Path(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 服务配置
class ServiceConfig:
    # Http服务配置
    HTTP_HOST = '0.0.0.0'
    HTTP_PORT = 8000
    HTTP_DEBUG = True
    HTTP_USE_RELOADER = False

    # Poll服务配置
    POLL_SLEEP_TIME = 0.5 # 0.5秒

    # mesg服务配置
    MESG_RECV_TIMEOUT = 0.5 # 0.5秒

    # Consul配置
    CONSUL_HOST = '172.16.1.84'
    CONSUL_PORT = 8500

    # 服务配置
    HEALTH_CHECK_TIMEOUT    = '5s'
    HEALTH_CHECK_INTERVAL   = '10s'
    HEALTH_CHECK_DEREGISTER = '15s'
    
    # 设备服务配置
    DEVICE_SERVICE_NAME = 'device-service'
    DEVICE_SCAN_INTERVAL = 0.5 # 0.5秒
    # 设备数据传输端口，硬编码，不允许修改
    DEVICE_UITEST_PORT = 8012
    DEVICE_FRAME_PORT = 8022
    DEVICE_UITREE_PORT = 8032
    DEVICE_PERF_PORT = 8042

    # ZMQ配置
    ZMQ_CLIENT_HOST = '172.16.1.84'
    ZMQ_TIMEOUT = 500 # ms
    ZMQ_REP_PORT = 5555
    ZMQ_PUB_PORT = 5556
    ZMQ_AIO_PORT = 5557

    # WebRTC配置
    WEBRTC_ICE_SERVERS = [
        { 'urls': 'stun:stun.l.google.com:19302' },
        { 'urls': 'stun:stun1.l.google.com:19302' },
        { 'urls': 'stun:stun2.l.google.com:19302' },
        { 'urls': 'stun:stun3.l.google.com:19302' },
        { 'urls': 'stun:stun4.l.google.com:19302' },
        {
            'urls': 'turn:172.16.1.84:3478',
            'username': 'smartest',
            'credential': 'smartest123'
        }
    ]
    WEBRTC_FRAME_RATE = 30
    WEBRTC_VIDEO_QUALITY = 80

# 数据库配置
class DatabaseConfig:
    DB_TYPE = 'ZODB'  # 可选: zodb, sqlite, mysql, postgresql
    DB_HOST = None
    DB_PORT = None
    DB_PATH = os.path.join(WORK_PATH, 'database', 'smartest.fs')
    DB_TIMEOUT = None  # None表示不设置超时
    DB_USER = None
    DB_PASSWORD = None
    

# 安全配置
class SecurityConfig:
    SECRET_KEY = 'smartest_secret_key_change_in_production'
    TOKEN_EXPIRE_HOURS = 24
    PASSWORD_SALT = 'smartest_salt_change_in_production'

# 日志配置
class LogConfig:
    LOG_DIR = os.path.join(WORK_PATH, 'logs')
    LOG_LEVEL = 'DEBUG'  # DEBUG, INFO, WARNING, ERROR, CRITICAL
    LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    LOG_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
    LOG_FILE_MAX_BYTES = 10 * 1024 * 1024  # 10MB
    LOG_FILE_BACKUP_COUNT = 5

# 加载自定义配置
def load_configs(work_path: str, config_file: str):
    """
    从JSON配置文件加载配置并更新配置类
    
    Args:
        work_path: 项目根目录路径
        config_file: 配置文件相对于work_path的相对路径
    
    Returns:
        bool: 加载成功返回True，失败返回False
    """
    import json
    from pathlib import Path
    
    try:
        # 构建配置文件的绝对路径
        config_path = Path(work_path) / config_file
        
        # 检查配置文件是否存在
        if not config_path.exists():
            print(f"配置文件不存在: {config_path}")
            return False
        
        # 读取JSON配置文件
        with open(config_path, 'r', encoding='utf-8') as f:
            config_data = json.load(f)
        
        # 更新全局WORK_PATH
        global WORK_PATH
        WORK_PATH = Path(work_path)
        
        # 更新服务配置
        if 'service' in config_data:
            service_config = config_data['service']
            
            # 代理服务配置
            if 'http' in service_config:
                http = service_config['http']
                if 'host' in http:
                    ServiceConfig.HTTP_HOST = http['host']
                if 'port' in http:
                    ServiceConfig.HTTP_PORT = http['port']
                if 'debug' in http:
                    ServiceConfig.HTTP_DEBUG = http['debug']
                if 'use_reloader' in http:
                    ServiceConfig.HTTP_USE_RELOADER = http['use_reloader']
            
            # 消息服务配置
            if 'mesg' in service_config:
                mesg = service_config['mesg']
                if 'recv_timeout' in mesg:
                    ServiceConfig.MESG_RECV_TIMEOUT = mesg['recv_timeout']
            
            # Poll服务配置
            if 'poll' in service_config:
                poll = service_config['poll']
                if 'sleep_time' in poll:
                    ServiceConfig.POLL_SLEEP_TIME = poll['sleep_time']
            
            # Consul配置
            if 'consul' in service_config:
                consul = service_config['consul']
                if 'host' in consul:
                    ServiceConfig.CONSUL_HOST = consul['host']
                if 'port' in consul:
                    ServiceConfig.CONSUL_PORT = consul['port']
            
            # 健康检查配置
            if 'health_check' in service_config:
                health = service_config['health_check']
                if 'timeout' in health:
                    ServiceConfig.HEALTH_CHECK_TIMEOUT = health['timeout']
                if 'interval' in health:
                    ServiceConfig.HEALTH_CHECK_INTERVAL = health['interval']
                if 'deregister' in health:
                    ServiceConfig.HEALTH_CHECK_DEREGISTER = health['deregister']
            
            # 设备服务配置
            if 'device' in service_config:
                device = service_config['device']
                if 'service_name' in device:
                    ServiceConfig.DEVICE_SERVICE_NAME = device['service_name']
                if 'scan_interval' in device:
                    ServiceConfig.DEVICE_SCAN_INTERVAL = device['scan_interval']
            
            # ZMQ配置
            if 'zmq' in service_config:
                zmq = service_config['zmq']
                if 'host' in zmq:
                    ServiceConfig.ZMQ_CLIENT_HOST = zmq['host']
                if 'timeout' in zmq:
                    ServiceConfig.ZMQ_TIMEOUT = zmq['timeout']
                if 'rep_port' in zmq:
                    ServiceConfig.ZMQ_REP_PORT = zmq['rep_port']
                if 'pub_port' in zmq:
                    ServiceConfig.ZMQ_PUB_PORT = zmq['pub_port']
                if 'aio_port' in zmq:
                    ServiceConfig.ZMQ_AIO_PORT = zmq['aio_port']
            
            # WebRTC配置
            if 'webrtc' in service_config:
                webrtc = service_config['webrtc']
                if 'ice_servers' in webrtc:
                    ServiceConfig.WEBRTC_ICE_SERVERS = webrtc['ice_servers']
                if 'frame_rate' in webrtc:
                    ServiceConfig.WEBRTC_FRAME_RATE = webrtc['frame_rate']
                if 'video_quality' in webrtc:
                    ServiceConfig.WEBRTC_VIDEO_QUALITY = webrtc['video_quality']
        
        # 更新数据库配置
        if 'database' in config_data:
            db_config = config_data['database']
            if 'type' in db_config:
                DatabaseConfig.DB_TYPE = db_config['type']
            if 'host' in db_config:
                DatabaseConfig.DB_HOST = db_config['host']
            if 'port' in db_config:
                DatabaseConfig.DB_PORT = db_config['port']
            if 'path' in db_config and db_config['path']:
                # 将相对路径转换为绝对路径
                DatabaseConfig.DB_PATH = str(Path(work_path) / db_config['path'])
            if 'timeout' in db_config:
                DatabaseConfig.DB_TIMEOUT = db_config['timeout']
            if 'user' in db_config:
                DatabaseConfig.DB_USER = db_config['user']
            if 'password' in db_config:
                DatabaseConfig.DB_PASSWORD = db_config['password']
        
        # 更新安全配置
        if 'security' in config_data:
            security_config = config_data['security']
            if 'secret_key' in security_config:
                SecurityConfig.SECRET_KEY = security_config['secret_key']
            if 'token_expire_hours' in security_config:
                SecurityConfig.TOKEN_EXPIRE_HOURS = security_config['token_expire_hours']
            if 'password_salt' in security_config:
                SecurityConfig.PASSWORD_SALT = security_config['password_salt']
        
        # 更新日志配置
        if 'log' in config_data:
            log_config = config_data['log']
            if 'dir' in log_config and log_config['dir']:
                # 将相对路径转换为绝对路径
                LogConfig.LOG_DIR = str(Path(work_path) / log_config['dir'])
            if 'level' in log_config:
                LogConfig.LOG_LEVEL = log_config['level']
            if 'format' in log_config:
                LogConfig.LOG_FORMAT = log_config['format']
            if 'date_format' in log_config:
                LogConfig.LOG_DATE_FORMAT = log_config['date_format']
            if 'file_max_bytes' in log_config:
                LogConfig.LOG_FILE_MAX_BYTES = log_config['file_max_bytes']
            if 'file_backup_count' in log_config:
                LogConfig.LOG_FILE_BACKUP_COUNT = log_config['file_backup_count']
        
        # 确保必要的目录存在
        os.makedirs(LogConfig.LOG_DIR, exist_ok=True)
        if DatabaseConfig.DB_PATH:
            db_dir = os.path.dirname(DatabaseConfig.DB_PATH)
            if db_dir:
                os.makedirs(db_dir, exist_ok=True)
        
        return True
        
    except json.JSONDecodeError as e:
        print(f"JSON配置文件格式错误: {e}")
        return False
    except Exception as e:
        print(f"加载配置文件时发生错误: {e}")
        return False
